package com.catazy.mvvmlib.ext

import java.lang.StringBuilder

/**
 * 作者: Tao
 * 日期: 2024/1/25
 * 时间: 15:04
 * 描述: 字节和字符串互转扩展类
 */

/**
 * 字节数组转字符串
 */
fun ByteArray.toHexString(): String {
    val result = StringBuilder()
    for (i in this.indices) {
        var hexString = Integer.toHexString(0xFF and this[i].toInt())
        if (hexString.length == 1) {
            hexString = "0$hexString"
        }
        result.append(hexString)
    }
    return result.toString()
}

/**
 * 字符串转字节数组
 */
fun String.hexToByteArray(): ByteArray {
    val len = this.length / 2
    val result = ByteArray(len)
    for (i in 0 until len) {
        result[i] = this.substring(i * 2, i * 2 + 2).toInt(16).toByte()
    }
    return result
}